package com.dev.lamp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.analysis.StoreHouse;

public class Recorder extends Thread {

	private boolean goon = true;

	public void run() {
		while (goon) {
			String str = readString();
			if (str != null && !"".equals(str)) {
				System.out.println("[" + str + "]");
				search(str);
			}
			try {
				Thread.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void search(String str) {
		Boolean on = null;
		if (str.contains("关灯")) {
			on = false;
		}
		if (str.contains("开灯")) {
			on = true;
		}
		if (on == null) {
			if (str.contains("关") || str.contains("开")) {
				String newStr = readString();
				String temp = str + newStr;
				if (temp.contains("关灯")||(temp.contains("关")&&temp.contains("灯"))) {
					on = false;
				} else if (temp.contains("开灯")||(temp.contains("开")&&temp.contains("灯"))) {
					on = true;
				}
			}
		}
		if (on != null) {
			Noticer noticer = new Noticer();
			if (on) {
				noticer.openLamp();
			} else {
				noticer.closeLamp();
			}
		}
	}

	private String readString() {
		StringBuffer bf = new StringBuffer();
		String text = StoreHouse.getPackage();
		if (text != null) {
			JSONObject json1 = JSON.parseObject(text);
			JSONArray arr1 = (JSONArray) json1.get("ws");
			for (Object obj2 : arr1) {
				JSONObject json2 = (JSONObject) obj2;
				JSONArray arr2 = (JSONArray) json2.get("cw");
				for (Object obj3 : arr2) {
					JSONObject json3 = (JSONObject) obj3;
					String v = json3.getString("w");
					bf.append(v);
				}
			}
		}
		return bf.toString();
	}
	
}
